import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'package:flutter/rendering.dart';

/// 自定义滚动物理效果，可动态控制是否禁止向上滚动
class DirectionalScrollPhysics extends ScrollPhysics {
  final bool restrictUpScroll; // true: 禁止向上滚动，仅允许向下滚动

  const DirectionalScrollPhysics({
    super.parent,
    required this.restrictUpScroll,
  });

  @override
  DirectionalScrollPhysics applyTo(ScrollPhysics? ancestor) {
    return DirectionalScrollPhysics(
      parent: buildParent(ancestor),
      restrictUpScroll: restrictUpScroll,
    );
  }

  @override
  bool shouldAcceptUserOffset(ScrollMetrics position) {
    if (restrictUpScroll) {
      // 通过扩展方法获取滚动方向，修复错误
      return getScrollDirection(position) == ScrollDirection.reverse;
    }
    return true; // 不限制时接受所有方向手势
  }

  @override
  Simulation? createBallisticSimulation(
    ScrollMetrics position,
    double velocity,
  ) {
    if (restrictUpScroll && velocity > 0) {
      // 限制时禁止向上的惯性滚动（velocity>0表示向上滚动趋势）
      return null;
    }
    return super.createBallisticSimulation(position, velocity);
  }

  // 扩展方法：从ScrollMetrics获取滚动方向
  ScrollDirection getScrollDirection(ScrollMetrics metrics) {
    if (metrics is ScrollPosition) {
      return metrics.userScrollDirection;
    }
    //  fallback逻辑：根据当前位置和初始位置判断
    if (metrics.pixels > metrics.minScrollExtent) {
      return ScrollDirection.reverse;
    }
    return ScrollDirection.forward;
  }
}
